"""import random
from deap import base, creator, tools, algorithms
import numpy as np


# 目标函数：计算个体的适应度值
def value_nonlcon(individual, params):
    x, y, z = individual
    return (x ** 2 + y ** 2 + z ** 2,)


# 遗传算法参数类
class GAParams:
    def __init__(self):
        # 最小化问题的适应度权重
        self.fitness_weight = -1.0

        # 个体属性：在[-20, 20]范围内随机生成浮点数
        self.attr_float_range = (-20, 20)

        # 个体由3个浮点数组成
        self.individual_length = 3

        # 种群规模
        self.population_size = 1000

        # 最大迭代次数
        self.ngen = 200

        # 交叉概率
        self.cxpb = 0.5

        # 变异概率
        self.mutpb = 0.2

        # 锦标赛选择的大小
        self.tournsize = 3

        # 评估函数的额外参数（虽然这里未使用，但保留以供扩展）
        self.evaluate_params = (0, 3)


# 初始化遗传算法的基本组件和工具箱
def initialize_ga(params):
    creator.create("FitnessMin", base.Fitness, weights=(params.fitness_weight,))
    creator.create("Individual", list, fitness=creator.FitnessMin)

    toolbox = base.Toolbox()

    toolbox.register("attr_float", random.uniform, *params.attr_float_range)
    toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, params.individual_length)
    toolbox.register("population", tools.initRepeat, list, toolbox.individual)

    toolbox.register("mate", tools.cxBlend, alpha=0.5)
    toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=params.mutpb)
    toolbox.register("select", tools.selTournament, tournsize=params.tournsize)
    toolbox.register("evaluate", value_nonlcon, params=params.evaluate_params)

    return toolbox


# 遗传算法主函数
def run_ga(params):
    toolbox = initialize_ga(params)

    # 初始化种群
    population = toolbox.population(n=params.population_size)

    # 遗传算法主循环
    for gen in range(params.ngen):
        offspring = algorithms.varAnd(population, toolbox, params.cxpb, params.mutpb)

        fits = map(toolbox.evaluate, offspring)
        for fit, ind in zip(fits, offspring):
            ind.fitness.values = fit

        population[:] = toolbox.select(offspring, k=len(population))

        best_fitness = min([ind.fitness.values[0] for ind in population])
        print(f"Generation {gen}: Best fitness = {best_fitness}")

    # 输出最终的最优解
    best_individual = tools.selBest(population, 1)[0]
    print("\n最优解:")
    print(best_individual)
    print("最优值:")
    print(best_individual.fitness.values[0])


# 创建遗传算法参数实例并运行遗传算法
if __name__ == "__main__":
    ga_params = GAParams()
    run_ga(ga_params)"""

"""import pygame
import time
import random
import heapq

# Initialize the pygame
pygame.init()

# Define colors
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

# Set the width and height of the game window
dis_width = 800
dis_height = 600

# Create the game window
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game with AI')

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 15

font_style = pygame.font.SysFont(None, 50)
score_font = pygame.font.SysFont(None, 35)

def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])

def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])

def a_star_search(start, goal, obstacles):
    def heuristic(a, b):
        return abs(a[0] - b[0]) + abs(a[1] - b[1])

    queue = []
    heapq.heappush(queue, (0, start))
    came_from = {}
    cost_so_far = {}
    came_from[start] = None
    cost_so_far[start] = 0

    while queue:
        current = heapq.heappop(queue)[1]

        if current == goal:
            break

        neighbors = [(current[0] + snake_block, current[1]), (current[0] - snake_block, current[1]),
                     (current[0], current[1] + snake_block), (current[0], current[1] - snake_block)]

        for next in neighbors:
            if next in obstacles or next[0] < 0 or next[1] < 0 or next[0] >= dis_width or next[1] >= dis_height:
                continue
            new_cost = cost_so_far[current] + 1
            if next not in cost_so_far or new_cost < cost_so_far[next]:
                cost_so_far[next] = new_cost
                priority = new_cost + heuristic(goal, next)
                heapq.heappush(queue, (priority, next))
                came_from[next] = current

    if goal not in came_from:
        return []

    path = []
    current = goal
    while current != start:
        path.append(current)
        current = came_from[current]
    path.reverse()
    return path

def game_loop():
    game_over = False
    game_close = False

    x1 = dis_width / 2
    y1 = dis_height / 2

    x1_change = 0
    y1_change = 0

    snake_list = []
    length_of_snake = 1

    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close == True:
            dis.fill(blue)
            message("You Lost! Press Q-Quit or C-Play Again", red)
            pygame.display.update()

            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        game_loop()

        # AI decision-making
        snake_head = (x1, y1)
        snake_body = set((x, y) for x, y in snake_list)
        path = a_star_search(snake_head, (foodx, foody), snake_body)

        if path:
            next_move = path[0]
            x1_change = next_move[0] - x1
            y1_change = next_move[1] - y1
        else:
            # No path found, move randomly to avoid infinite loop
            x1_change, y1_change = random.choice([(snake_block, 0), (-snake_block, 0), (0, snake_block), (0, -snake_block)])

        x1 += x1_change
        y1 += y1_change

        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0 or (x1, y1) in snake_body:
            game_close = True

        dis.fill(blue)
        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
        snake_head = []
        snake_head.append(x1)
        snake_head.append(y1)
        snake_list.append(snake_head)
        if len(snake_list) > length_of_snake:
            del snake_list[0]

        for x in snake_list[:-1]:
            if x == snake_head:
                game_close = True

        our_snake(snake_block, snake_list)
        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            length_of_snake += 1

        clock.tick(snake_speed)

    pygame.quit()
    quit()

game_loop()
"""

"""import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 加载数据
data = {
    '商品详情页停留时长（秒）(X1)': [120, 30, 200, 10, 80, 50, 250, 5, 150, 40, 300, 15, 180, 60, 350, 8, 130, 35, 280, 12, 170, 50, 400, 20, 100, 40, 320, 18, 220, 60, 450, 10, 160, 45, 380, 6, 140, 30, 300, 15, 200, 55, 420, 25, 120, 35, 350, 20, 250, 70, 180, 40, 480, 18, 110, 30, 360, 12, 280, 50, 400, 20, 190, 60, 500, 10, 170, 40, 330, 20, 230, 50, 450, 25, 140, 30, 380, 18, 260, 60, 210, 40, 500, 20, 130, 30, 390, 15, 300, 50, 420, 20, 200, 60, 550, 10, 180, 40, 340, 20],
    '商品价格满意度评分（满分10分）(X2)': [8, 4, 9, 2, 7, 5, 10, 1, 8, 6, 9, 3, 8, 6, 10, 1, 8, 5, 9, 2, 8, 6, 10, 4, 7, 5, 9, 3, 8, 6, 10, 2, 8, 5, 9, 1, 8, 5, 9, 3, 8, 6, 10, 4, 7, 5, 9, 6, 8, 6, 9, 6, 8, 6, 10, 4, 7, 5, 9, 3, 8, 6, 10, 4, 8, 6, 10, 4, 8, 6, 10, 4, 8, 6, 10, 4, 8, 6, 10, 4, 8, 6, 10, 4, 8, 6, 10, 4, 8, 6, 10, 4, 8, 6, 10, 4, 8, 6, 10, 4],
    '店铺综合信誉评分（满分100分）(X3)': [80, 60, 90, 40, 70, 50, 95, 30, 85, 65, 98, 50, 82, 60, 100, 20, 80, 55, 92, 45, 88, 68, 100, 50, 75, 50, 95, 40, 88, 65, 100, 30, 82, 58, 98, 20, 80, 55, 92, 45, 88, 68, 100, 50, 75, 50, 95, 65, 88, 50, 95, 65, 88, 68, 100, 50, 77, 58, 98, 40, 84, 60, 96, 50, 85, 63, 100, 30, 80, 59, 94, 40, 88, 67, 98, 50, 75, 50, 95, 40, 88, 65, 96, 50, 85, 63, 100, 30, 80, 59, 94, 40, 88, 67, 98, 50, 75, 50, 95, 40, 88, 65],
    '用户过往1年购买频次（次）(X4)': [5, 1, 8, 0, 3, 2, 10, 0, 6, 2, 12, 1, 7, 3, 15, 0, 5, 2, 9, 1, 7, 3, 20, 1, 4, 2, 11, 1, 8, 3, 25, 0, 6, 2, 13, 0, 5, 2, 9, 1, 8, 3, 20, 1, 4, 2, 11, 3, 8, 3, 11, 3, 8, 3, 25, 1, 4, 2, 13, 1, 8, 2, 12, 1, 7, 3, 30, 0, 5, 2, 11, 1, 8, 3, 12, 1, 7, 3, 35, 0, 5, 2, 11, 1, 8, 3],
    '是否购买（1表示购买，0表示未购买）(Y)': [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
}

# 创建DataFrame
df = pd.DataFrame(data)

# 划分自变量和因变量
X = df[['商品详情页停留时长（秒）(X1)', '商品价格满意度评分（满分10分）(X2)', '店铺综合信誉评分（满分100分）(X3)', '用户过往1年购买频次（次）(X4)']].values
y = df['是否购买（1表示购买，0表示未购买）(Y)'].values

# 数据归一化（常用的归一化方式，这里简单示例）
X = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))

# 设置随机种子以便结果可复现
np.random.seed(42)
# 按7:3比例划分训练集和测试集
indices = np.arange(len(X))
np.random.shuffle(indices)
split_index = int(len(X) * 0.7)
X_train, X_test = X[indices[:split_index]], X[indices[split_index:]]
y_train, y_test = y[indices[:split_index]], y[indices[split_index:]]

# 构建前馈神经网络模型
model = tf.keras.Sequential([
    tf.keras.layers.Dense(64, activation='relu', input_shape=(4,)),  # 输入层，4个特征，64个节点，使用ReLU激活函数
    tf.keras.layers.Dense(32, activation='relu'),  # 隐藏层，32个节点，ReLU激活函数
    tf.keras.layers.Dense(1, activation='sigmoid')  # 输出层，输出概率值，使用Sigmoid激活函数用于二分类
])

# 选择损失函数和优化器
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# 训练模型，设置训练轮数为150轮（可根据实际情况调整），并记录训练过程中的历史数据
history = model.fit(X_train, y_train, epochs=150, batch_size=32, validation_split=0.2, verbose=1)

# 提取训练过程中的损失值用于监控
losses = history.history['loss']
val_losses = history.history['val_loss']

# 绘制损失值变化曲线
plt.plot(losses, label='Training Loss')
plt.plot(val_losses, label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Loss Curves during Training')
plt.legend()
plt.show()"""


import pyswarms as ps
import numpy as np

# 定义目标函数
def objective_function(x):
    return (x[:, 0] - 2)**2 + (x[:, 1] - 3)**2

# 定义变量的上下限
bounds = (np.array([0, 0]), np.array([5, 5]))

# 创建粒子群优化对象
optimizer = ps.single.GlobalBestPSO(n_particles=30, dimensions=2, options={'c1': 0.5, 'c2': 0.3, 'w': 0.9}, bounds=bounds)

# 执行优化
cost, pos = optimizer.optimize(objective_function, iters=100)

# 输出结果
print('最优解:', pos)
print('目标函数值:', cost)


































